var team_name = null;
var team_ID = null;
$(function(){


   $("#addTeam").click(function(){
      modalWindowHandler.setWindowPosition('center');
      modalWindowHandler.setModalWindowTitle("Add Team");
   modalWindowHandler.setContent('getAddTeamForm');

  //modalWindowHandler.AJAXCallbackFunction = ("setUpAddTeamModalWindow");
   modalWindowHandler.openModalWindow();
setUpAddTeamModalWindow();
    });

       $("#updateTeamRank").click(function(){
        modalWindowHandler.setWindowPosition('top');
         $( "#modalDialogWindow" ).children("#modalWindowContent").html("<div style='margin-top : 50px; text-align: center; vertical-align: middle; height: 100%;'><img src="+$('#loadingImage').val()+" align='middle' alt='Loading Pic is Missing' /></div>");
     $( "#modalDialogWindow" ).dialog('open');
    modalWindowHandler.setModalWindowTitle("Team Rank Manager");
   modalWindowHandler.setContent('getTeamRanksManager');
    modalWindowHandler.setWindowWidth('700')
   sendRequest.setAction('getTeamRanksManager');
sendRequest.setSendParameters({});
     $("#mask").load(sendRequest.serverURL,sendRequest.getSendData(),function (commentatorContent)
{
  $( "#modalDialogWindow" ).children("#modalWindowContent").html("<div style='margin-top : 50px; text-align: center; vertical-align: middle; height: 100%;'><img src="+$('#loadingImage').val()+" align='middle' alt='Loading Pic is Missing' /></div>");
$( "#modalDialogWindow" ).children("#modalWindowContent").hide();
$( "#modalDialogWindow" ).children("#modalWindowContent").delay(500).html($("#mask").html()).fadeIn('slow');
$("#mask").empty();
$(".errorMessageDiv").hide();
  // modalWindowHandler.openModalWindow();
   $( "#unranked, #ranked" ).sortable({
			placeholder: "ui-state-highlight",
                        items: "li:not(.ui-state-disabled)",
                        connectWith: ".connectedSortable"
		});
});

setUpTeamRanksManager();
    });

$("#deleteTeam").click(function(){
    modalWindowHandler.setWindowPosition('center');
     $( "#modalDialogWindow" ).children("#modalWindowContent").html("<div style='margin-top : 50px; text-align: center; vertical-align: middle; height: 100%;'><img src="+$('#loadingImage').val()+" align='middle' alt='Loading Pic is Missing' /></div>");
     $( "#modalDialogWindow" ).dialog('open');
   modalWindowHandler.setModalWindowTitle("Remove Team");
   modalWindowHandler.setContent('getDeleteTeamForm');
    modalWindowHandler.setWindowWidth('500')
   sendRequest.setAction('getDeleteTeamForm');
sendRequest.setSendParameters({});
     $("#mask").load(sendRequest.serverURL,sendRequest.getSendData(),function (commentatorContent)
{
  $( "#modalDialogWindow" ).children("#modalWindowContent").html("<div style='margin-top : 50px; text-align: center; vertical-align: middle; height: 100%;'><img src="+$('#loadingImage').val()+" align='middle' alt='Loading Pic is Missing' /></div>");
$( "#modalDialogWindow" ).children("#modalWindowContent").hide();
$( "#modalDialogWindow" ).children("#modalWindowContent").delay(500).html("<span class='errorMessageDiv'></span><div id='deleteTeamListContent'>"+$("#mask").html()+"</div>").fadeIn('slow');
$("#mask").empty();
$(".errorMessageDiv").hide();
  // modalWindowHandler.openModalWindow();
     setUpDeleteTeamManager();

});
    //  modalWindowHandler.openModalWindow();
   
});




});

function setUpDeleteTeamManager()
{

$("#modalDialogWindow").dialog( "option", "buttons", {
            "Delete Team": function() {

            },
            "Close": function() {
                jQuery(this).dialog('close');

            }

        });

                                                $(".ui-dialog-buttonpane button:contains('Delete Team')").click(function(){
                                         //   $( "#modalDialogWindow" ).dialog('close');
                                              $(".ui-dialog-buttonpane button:contains('Delete Team')").unbind();
                                         $( "#modalDialogWindow" ).children("#modalWindowContent").append('<div id="deleteConfirmation"><p><span class="ui-icon ui-icon-alert" style="float:left; margin:0 7px 20px 0;"></span>The team '+team_name+' will be permanently deleted and cannot be recovered. Addtionally, all players belonging to this team will be deleted as well. Are you sure you want delete this team?</p></div>');
                                         $("#deleteConfirmation").hide();
                                         $('#deleteTeamListContent').hide('blind',{},800);
                                         $("#deleteConfirmation").delay(1100).fadeIn('slow');
                                         $( "#modalDialogWindow" ).dialog( "option", "title", 'Confirm Team Delete : '+team_name );

                                         $(".ui-dialog-buttonpane button:contains('Delete Team')").click(function(){

                                                   $(".ui-dialog-buttonpane button:contains('Delete Team')").unbind();
                                        var teamData = {"teamName": team_name, "teamID":team_ID };
                                               sendRequest.setAction('deleteTeam');
                                            sendRequest.setSendParameters(teamData);

                                                 $(".errorMessageDiv").load(sendRequest.serverURL,sendRequest.getSendData(),function (response)
                                            {

                                            var deleteSuccess = ($('.errorMessageDiv').html()).replace(/^\s*|\s*$/g,'');
                                            if (deleteSuccess == '1')
                                                {
                                                    $( "#modalDialogWindow" ).children("#modalWindowContent").hide();
                                                     $( "#modalDialogWindow" ).dialog( "option", "title", 'Delete Successful : '+team_name );
                                                                  $(".ui-dialog-buttonpane button:contains('Delete Team')").children('span').text('OK');
                                                  $( "#modalDialogWindow" ).children("#modalWindowContent").html('<div id="deleteConfirmation"><p><span class="ui-icon ui-icon-check" style="float:left; margin:0 7px 20px 0;"></span>The team '+team_name+' has been deleted successfully. All players belonging to this team have been succcessfully deleted as well.</p></div>');
                                                $( "#modalDialogWindow" ).children("#modalWindowContent").show('bounce',{},500);
                                                           updateTeamList();
                                                        $(".ui-dialog-buttonpane button:contains('OK')").click(function(){
                                                               $( "#modalDialogWindow" ).dialog('close');
                                                        });
                                            }
                                                else
                                                    {
                                                         formValidator.updateErrorMessage("Delete of team has failed. Please contact your software administrator.");

                                                    }
                                            });

                                         });

                                        });
            $(".ui-dialog-buttonpane button:contains('Delete Team')").button("disable");


$( "#deleteTeam-selectable" ).selectable({
			stop: function() {
				var result = $( "#select-result" );
				$( ".ui-selected", this ).each(function() {
					var index = $( "#deleteTeam-selectable li" ).index( this );
                                        team_ID =$(this).attr('name');
                                         team_name = $(this).text();
					result.html(  ( team_name ) );
                                        var relTeamIndex = parseInt(index+1);
                                        if (relTeamIndex < 1 || result.text().length<1)
                                         {
                                        $(".ui-dialog-buttonpane button:contains('Delete Team')").button("disable");
                                         }
                                         else
                                             {
                                        $(".ui-dialog-buttonpane button:contains('Delete Team')").button("enable");

                                      //  $( "#modalDialogWindow" ).dialog({ buttons: { "Delete Team": function() { $(this).dialog("close"); } } });
                                             }

				});
			}
		});
}

function setUpTeamRanksManager()
{

$("#modalDialogWindow").dialog( "option", "buttons", {
            "Set Team Rank": function() {
 var rankedTeamOrder = jQuery("#ranked").sortable('toArray').toString();
  var unrankedTeamOrder = jQuery("#unranked").sortable('toArray').toString();
$( "#modalDialogWindow" ).children("#modalWindowContent").hide();
 $( "#modalDialogWindow" ).children("#modalWindowContent").html("<div style='margin-top : 50px; text-align: center; vertical-align: middle; height: 100%;'><img src="+$('#loadingImage').val()+" align='middle' alt='Loading Pic is Missing' /></div>").fadeIn('slow');

   var rankedTeamOrderArray = rankedTeamOrder.split(',');
 var rankedTeamORderJSON = JSON.stringify(rankedTeamOrderArray);


 var unrankedTeamOrderArray = unrankedTeamOrder.split(',');
 var unrankedTeamORderJSON = JSON.stringify(unrankedTeamOrderArray);
var updateTeamData = {"unrankedTeams": unrankedTeamORderJSON, "rankedTeams":rankedTeamORderJSON };
   sendRequest.setAction('updateTeamRankings');
sendRequest.setSendParameters(updateTeamData);

     $("#mask").load(sendRequest.serverURL,sendRequest.getSendData(),function (response)
{
 $("#mask").empty();
$( "#modalDialogWindow" ).delay(1000).dialog('close');
           updateTeamList();
});

$(".errorMessageDiv").html(updateTeamData);

            },
            "Close": function() {
                jQuery(this).dialog('close');

            }

        });
}



function setUpAddTeamModalWindow()
{


   $("#modalDialogWindow").dialog( "option", "buttons", {
            "Add Team": function() {

    var teamName = jQuery(':input[id=teamName]');
    var shortName = jQuery(':input[id=shortName]');
    var allFields = jQuery([]).add(teamName).add(shortName);
                var bValid = true;
                allFields.removeClass('ui-state-error');

                bValid = bValid && formValidator.checkLength(teamName,"your team name",3,20);
                bValid = bValid && formValidator.checkRegexp(teamName,/^[abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789\s]*$/,"The team name field only allows alphanumeric characters (a-z 0-9).");
                bValid = bValid && formValidator.checkLength(shortName,"your team's short name",2,7);
                bValid = bValid && formValidator.checkRegexp(shortName,/^([0-9a-zA-Z])+$/,"The short team name field only allows alphanumeric characters (a-z 0-9 IND, PAK, ZA, etc).");

                if (bValid) {


    var hiddenResponseDiv = jQuery('.responseDiv');
    hiddenResponseDiv.hide();

                    sendRequest.setAction('insertNewTeam');
                formData = {
                        'teamName':teamName.val(),
                        'shortName':shortName.val()
                    }
               
                    sendRequest.setSendParameters(formData);
             
                    hiddenResponseDiv.load(sendRequest.serverURL, sendRequest.getSendData(), function(){
                        hiddenResponseDiv.unbind();
                        var registrationResponse = (hiddenResponseDiv.html()).replace(/^\s*|\s*$/g,'');
                       ;
                        if (formValidator.hasNumbers(registrationResponse))
                            {
                     $( "#teamList" ).html("<div style='margin-top : 50px; text-align: center; vertical-align: middle; height: 100%;'><img src="+$('#loadingImage').val()+" align='middle' alt='Loading Pic is Missing' /></div>");
                      $("#modalDialogWindow").dialog('close');
                jQuery('.errorMessageDiv').html('');
                jQuery(':input[id=teamName]').val('');
                jQuery(':input[id=shortName]').val('');
                  updateTeamList();
                            }
                            else
                                {
                             teamName.addClass('ui-state-error');
                             formValidator.updateErrorMessage("Team Name Already Exists. Please select another Team Name");
                                }
                    });
                }
            },
            "Cancel": function() {
                jQuery(this).dialog('close');
                jQuery('.errorMessageDiv').html('');
                jQuery(':input[id=teamName]').val('');
                jQuery(':input[id=shortName]').val('');
             
            }

        });
}

function updateTeamList()
{
       sendRequest.setAction('updateTeamList');

                    sendRequest.setSendParameters({});
                    $('#mask').load(sendRequest.serverURL, sendRequest.getSendData(), function(){
  $( "#teamList" ).html("<div style='margin-top : 50px; text-align: center; vertical-align: middle; height: 100%;'><img src="+$('#loadingImage').val()+" align='middle' alt='Loading Pic is Missing' /></div>");
 $( "#teamList" ).hide();
 $( "#teamList" ).delay(500).html($("#mask").html()).fadeIn('slow');
$("#mask").empty();
                    });
}